
import { debounce } from 'lodash';
export const debouncedToLogin = debounce(() => {
    uni.redirectTo({
        url: '/pages/login'
    });
}, 500); // 1000ms内只会执行一次

// 配置基础URL 
export const baseURL = 'https://wanxuanhuishou.kuanlaoban.com';

// 处理URL函数
const processUrl = (url) => {
    if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
    }
    return `${baseURL}${url.startsWith('/') ? url : `/${url}`}`;
};

// 请求配置
const defaultConfig = {
    baseURL,
    timeout: 10000,
    header: {
        'Content-Type': 'application/json'
    }
};

// 请求拦截
const requestInterceptor = (config) => {
    const token = uni.getStorageSync('token');
    if (token) {
        config.header['token'] = token;
    }
    return config;
};

// 响应拦截
const responseInterceptor = (response) => {
    const { statusCode, data } = response;
    // 请求成功
    if (statusCode === 200) {
        // 这里可以根据后端的数据结构进行调整
        if (data.code === 1) {
            return data;
        } else {
            const error = new Error(data.msg || "请求失败");
            error.code = data.code;
            throw error;
        }
    }

    // 请求失败
    const error = new Error(response.data?.msg || '网络请求失败');
    error.statusCode = statusCode;
    throw error;
};

// 错误处理
const errorHandler = (error) => {
    const statusCode = error.statusCode;

    // 处理特定状态码
    switch (statusCode) {
        case 401:
            uni.removeStorageSync("token");
            uni.removeStorageSync("userInfo");
            uni.showModal({
                title: '登录',
                content: '请登录',
                showCancel: false,
                confirmText: '去登录',
                success: ({ confirm }) => {
                    if (confirm) {
                        if (getCurrentPages()[getCurrentPages().length - 1].route == 'pages/login/index') {
                            return;
                        } else {
                            debouncedToLogin();
                        }
                    }
                }
            });


        case 403:
            uni.showToast({
                title: '没有权限',
                icon: 'none'
            });
            break;
        case 404:
            uni.showToast({
                title: '请求的资源不存在',
                icon: 'none'
            });
            break;
        case 500:
            uni.showToast({
                title: '服务器错误',
                icon: 'none'
            });
            break;
        default:
            uni.showToast({
                title: error.message || '请求失败',
                icon: 'none'
            });
    }

    return Promise.reject(error);
};

// 创建请求方法
const request = (options) => {
    const config = {
        ...defaultConfig,
        ...options,
        url: processUrl(options.url), // 处理URL
        header: {
            ...defaultConfig.header,
            ...options.header
        }
    };

    // 应用请求拦截器
    const interceptedConfig = requestInterceptor(config);

    return new Promise((resolve, reject) => {
        uni.request({
            ...interceptedConfig,
            success: (response) => {
                try {
                    const result = responseInterceptor(response);
                    resolve(result);
                } catch (error) {
                    errorHandler(error).catch(reject);
                }
            },
            fail: (error) => {
                errorHandler(error).catch(reject);
            }
        });
    });
};

// 封装常用请求方法
const http = {
    get: (url, params = {}, options = {}) => {
        return request({
            url,
            method: 'GET',
            data: params,
            ...options
        });
    },

    post: (url, data = {}, options = {}) => {
        return request({
            url,
            method: 'POST',
            data,
            ...options
        });
    },
};

export default http; 